//
//  SegmentedControl.swift
//  myhub
//
//  Created by x on 2024/6/2.
//

import UIKit
import RxSwift
import RxCocoa
import XDesignKit

open class SegmentedControl: UISegmentedControl {
    
    public let segmentSelection = BehaviorRelay<Int>(value: 0)

    
    public init() {
        super.init(items: [])
        makeUI()
    }

    public override init(items: [Any]?) {
        super.init(items: items)
        addTarget(self, action: #selector(segmentValueChanged), for: .valueChanged)
        makeUI()
    }

    public override init(frame: CGRect) {
        super.init(frame: frame)
        makeUI()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        makeUI()
    }
    open func makeUI() {
        themeService.typeStream.subscribe(onNext: { [weak self] (themeType) in
            let theme = themeType.associatedObject
            self?.backgroundColor = theme.primary
            let font = UIFont.DesignKit.small
            self?.setTitleTextAttributes([NSAttributedString.Key.font: font,
                                    NSAttributedString.Key.foregroundColor: theme.text], for: .normal)
            self?.setTitleTextAttributes([NSAttributedString.Key.font: font,
                                    NSAttributedString.Key.foregroundColor: theme.secondary], for: .selected)
            self?.setNeedsDisplay()
        }).disposed(by: rx.disposeBag)

        cornerRadius = Dimensions.cornerRadius
        updateUI()
    }

    @objc func segmentValueChanged(sender: UISegmentedControl) {
        let index = sender.selectedSegmentIndex
        self.segmentSelection.accept(index)
    }
    open func updateUI() {
        setNeedsDisplay()
    }
}
